﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Klinkby.Scheduler
{
    /// <summary>
    /// Specifies a time of day on a weekly basis for <see cref="Scheduler"/>.
    /// </summary>
    [Serializable]
    public class WeeklyInterval : MarshalByRefObject, IInterval
    {
        readonly DayOfWeek _dayOfWeek;
        readonly TimeSpan _timeOfDay;

        public WeeklyInterval(DayOfWeek dayOfWeek, TimeSpan timeOfDay)
        {
            if (timeOfDay.TotalHours >= 24)
                throw new ArgumentException("Must be less than 24 hours", "timeOfDay");
            _dayOfWeek = dayOfWeek;
            _timeOfDay = timeOfDay;
        }

        #region IInterval Members

        public DateTime Next
        {
            get
            {
                var now = DateTime.Now;
                int deltaDays = (_dayOfWeek - now.DayOfWeek);
                var next = now.AddDays(deltaDays).Date + _timeOfDay;
                return (next < now) 
                    ? next.AddDays(7)
                    : next;
            }
        }

        #endregion
    }

}
